/**
 * File with globally usable scripts
 * 
 * @author Erwin Goossen
 */

/**
 * Global variables
 */
var edit = false;
var timeoutId = null;

/**
 * Replace every strA with strB
 * @param Text in which to find and replace
 * @param strA Text or char to search for
 * @param strB Text or char to replace strA with
 * @return Text with replaced strA
 */ 
function replaceAll(text, strA, strB) {
    while ( text.indexOf(strA) != -1) {
        text = text.replace(strA,strB);
    }
    return text;
}

/**
 * Reformat time from msec to mm:ss
 * @param time in milliseconds
 * @return formatted time: mm:ss
*/
function calcTime(time) {
	time = parseInt(time/1000);
	var minutes = parseInt(time/60);
	var seconds = time%60 + '';
	if (seconds.length < 2) {
		seconds = '0' + seconds;
	}
	return minutes + ':' + seconds;
}


/**
 * Fill release combo with first chars of artists
 * @param none
 * @return will directly be visible in  html
*/
function fillReleaseCombo() {
	var result;
	try {
		result = getFirstChars();
		var listLength = result.data.length;
		var options = '<option value="">All</option>';
		$('#combo').append(options);
		for (i=0; i<listLength;i++) {
			options = '<option value="'+result.data[i].firstLetter+'">'+result.data[i].firstLetter+'</option>';
			$('#combo').append(options);
		}
	} 
	catch (e){
		var options = '<option value="">All</option>';
		$('#combo').append(options);
	}
}

/**
 * Show all releases stored in the db
 * @param value Empty string for all releases, or the first letter of the artistname.
 * @return direct Will directly be visible in  html
*/
function showReleases(value) {
	var artistName = '';
	var releaseList = '';
	var result = null;
	try {
		result = getReleaseList(value);
		var listLength = result.data.length;
		for (i=0; i<listLength; i++) {
			var mediaImg = "lib/img/cd.png";
			if (result.data[i].media == "LP") {
				mediaImg = "lib/img/lp.png";
			}
			if (result.data[i].name == artistName) {
				releaseList += createBlock(result.data[i].album_id,result.data[i].cover,result.data[i].title,mediaImg,result.data[i].year);
			}
			else {
				releaseList += createReleaseGroupHeader(result.data[i].name,result.data[i].artist_id);
				releaseList += createBlock(result.data[i].album_id,result.data[i].cover,result.data[i].title,mediaImg,result.data[i].year);
			}
			artistName = result.data[i].name;
		}
		$('#releaseBlock').html(releaseList);
	
		$('.blockList').mouseover(
		function(){
			$(this).find('.deleteBlock').addClass('show');
		});

		$('.blockList').mouseout(
		function(){
			$('.deleteBlock').removeClass('show');
		});

		$('.blockList').click(
		function() {
			showSelectedRelease($(this).attr('id'));
		});

		$('.deleteBlock').mouseover(
		function(){
			$('.blockList').unbind('click');
		});

		$('.deleteBlock').mouseout(
		function(){
			$('.blockList').click(
			function() {
				showSelectedRelease($(this).attr('id'));
			});
		});

		$('.ticket').click(
		function(){
			getConcertInfo($(this).attr('alt'));
		});

		$('.deleteBlock').click(
		function(){
			deleteAlbum($(this).attr('id'));
			showMessage('Verwijderd', '<br/><br/>Album verwijderd');
			showReleases($('#combo').val());
		});
	} catch(e) {
		releaseList += '<div class="releaseTitle" id="">Geen Resultaat!</div>';
		$('#releaseBlock').html(releaseList);
	}
}

/**
 * Show selected release
 * @param not Not implemented yet
 * @return Will directly be visible in  html
*/
function showSelectedRelease(release_id) {
	edit = false;
	var release = '';
	var result = getSelectedRelease(release_id);
	if (!result == ''){
		var dataLength = result.data.length;
		for (i = 0; i < dataLength; i++) {
			$('#releaseBlock').empty();
			curRelease.artist 	= result.data[i].name;
			curRelease.album 	= result.data[i].title;
			curRelease.albumYear = result.data[i].year;
			curRelease.cover 	= result.data[i].cover;
			curRelease.album_id	= release_id;
			release += releaseHead(true);
			$('#releaseBlock').append(release);
			// Found artist and album, now handle the titles
			var songs = getSongs(release_id);
			if (songs.data.length != 0) {
				curRelease.songs = []; //reset array
				lyrics = [];
				for (i = 0; i < songs.data.length; i++) {
					curRelease.songs[i] = [];
					curRelease.songs[i][0] = replaceAll(songs.data[i].name,"'","&acute;");
					curRelease.songs[i][1] = songs.data[i].duration;
					curRelease.songs[i][2] = songs.data[i].song_id;
				}
				$('#releaseBlock').append(showSongList());
			}
			else {
				showMessage('Resultaat', '<br/><br/>Geen songs gevonden');
			}
		}
	}		
	else{
		showMessage('Resultaat','<br/><br/>Album niet gevonden');
	}

	$('#backToList').click(
	function(){
		showReleases($('#combo').val());
	});

	$('#editSongs').click(
	function(){
		if (edit) {
			$(this).attr('src', '/lib/img/edit.png');
			edit = false;
		}
		else {
			$(this).attr('src', '/lib/img/edit_red.png');
			edit = true;
		}
	});
	
	$('.song').click(
	function() {
		if (edit) {
		createEdit($(this));
		}
	});
	
	$('.showLyric').click(
	function() {
		showLyrics($(this).attr('value'));
	});
}

/**
 * Create an editfield in the list
 * @param oblSong the element to turn inti an input
 * @return null Will directly be visible in  html
*/
function createEdit(objSong) {
		var htmlValue = '<input id="editTekst" type="text" value="' + objSong.html() + '" />';
		objSong.html(htmlValue);
		objSong.unbind('click');
		$('#editTekst').focus();
		$('#editTekst').blur(
		function() {
			saveSongChange(objSong);
		});
		
		$('#editTekst').keydown(
		function(event) {
			if (event.keyCode == '13') {
				saveSongChange(objSong);
			}
		});
}

/**
 * Saving the changed data of a song
 * @param {Object} objSong Object where to save from
 */
function saveSongChange(objSong) {
	var htmlValue = $('#editTekst').val();
	objSong.html(htmlValue);
	if (objSong.attr('id') == 'name') {
		updateSong(objSong.attr('value'), htmlValue, '');
	}
	else if (objSong.attr('id') == 'duration') {
		updateSong(objSong.attr('value'), '', htmlValue);
	}
	else if (objSong.attr('id') == 'year') {
		updateAlbum(objSong.attr('value'),objSong.text());
	}
	objSong.click(
	function(){
		if (edit) {
			createEdit($(this));
		}
	});
}

/**
 * Creates a block for the itemlist
 * @param {String} album_id ID of the album
 * @param {String} cover path of the coverimage
 * @param {String} title title of the album
 * @param {String} media cd/lp
 * @return {String} albumBlock Html-block with albuminfo
 */
function createBlock(album_id,cover,title,media,year) {
	albumBlock  = '<div class="blockList" id="'+album_id+'">';
    albumBlock += '<img src="'+cover+'" class="blockImage" />';
    albumBlock += '<div class="blockText">'+title+'<p>('+year+')</p></div>';
	albumBlock += '<div class="deleteBlock" id="'+album_id+'"></div>';
    albumBlock += '<div class="mediaImg"><img src="'+media+'" /></div>';
    albumBlock += '</div>';
	return albumBlock;
}

/**
 * Creates a groupheader for the itemlist
 * @param {String} name Name of the artist
 * @return {String} albumBlock Html-block with albuminfo
 */
function createReleaseGroupHeader(name,id) {
	var ReleaseGroupHeader = ''
	ReleaseGroupHeader += '<div class="releaseTitle" id=""><div class="left">' + name + '</div>';
	ReleaseGroupHeader += '<img id="'+id+'" class="ticket hide" src="lib/img/ticket.png" alt="'+name+'" /></div>'
	if (configFile.concert == 'true') {
		getConcertStatus(name,id);
	}
	return ReleaseGroupHeader;
}

/**
 * Shows a popUp with the given title and message
 * @param {String} title Text in titlebar of messagebox
 * @param {String} message Messagetext
 */
function showMessage(title, message) {
	$("span.ui-dialog-title").text(title);
	$('#alertMessage').css('visibility','visible');
	$('#alertMessage').html(message);
	$('#alertMessage').dialog('open');
}

function showLyrics(title) {
	getLyric(curRelease.artist, title);
	if (lyrics[0] != false) {
		var editUrl = 'http://lyricsfly.com/search/correction.php?' + lyrics[3] + '&id=' + lyrics[4];
		var content = createLyricContent();
		$('#lyricBox').css('visibility', 'visible');
		$('#lyricBox').html(content);
		$('#lyricBox').dialog({
			autoOpen: false,
			width: 400,
			height: 500,
			show: 'slide',
			buttons: {
				Print: function(){
					
				},
				Wijzig: function(){
					openExternalURL(editUrl);
				},
				Ok: function(){
					$(this).dialog('close');
					$('#lyricBox').unbind('dialog');
					$('#lyricBox').css('visibility', 'hidden');
				}
			},
			modal: true
		});
		$('span.ui-dialog-title').text(curRelease.artist + ' - ' +title);
		$('#lyricBox').dialog('open');
	}
}

function createLyricContent(){
	var lyric = replaceAll(lyrics[2],'[br]','<br />');
	var content = "<b>" + lyrics[1] + "</b><br />";
	content    += "<b>" + curRelease.artist + "</b><hr/>";
	content	   += lyric;
	return content;
}
/**
 * Get the year out if the date
 * @param {String} date
 */
function getYear(date) {
	var year = '';
	if (date.length > 4) {
		year = date.substring(0,4);
	}
	else {
		year = date;
	}
	return year;
}

/**
 * Creation of the header in releaseView
 * @param {String} album release to show
 * @param {String} artist artist name
 * @param {Integer} year year of the release (nnb if empty)
 * @param {String} cover url of the cover image
 * @param {String} release_id musicbrainz_id of the release
 * @param {String} show not implemented yet
 */
function releaseHead(show) {
	if (curRelease.albumYear.length == 0 || curRelease.albumYear == null) {
		curRelease.albumYear = 'nnb';
	}
	var release = '<div class="relArtist">' + curRelease.artist;
	release += '<div id="year" class="song rightCombo" value="' + curRelease.album_id + '">';
	release += curRelease.albumYear + '</div></div>';
	release += '<div id="relAlbum">' + curRelease.album ;
	if (show) {
		release += '<span class="backButton"><img src="lib/img/back.png" id="backToList" title="Terug"/></span>';
		release += '<span class="backButton"><img src="lib/img/edit.png" id="editSongs" title="Edit"/></span></div><hr />';
		release += '<img src="' + curRelease.cover + '" id="cover" title="hoes"/>';
	}
	else {
		release += '<select id="media" class="right rightCombo">';
		release += '<option value="CD" selected>CD</option><option value="LP">LP</option>';
		release += '</select></div><hr />';
	}
	return release;
}

function showSongList() {
	var result = '';
	for (i = 0; i < curRelease.songs.length; i++) {
		var style = 'odd';
		if (i%2 == 0){
			style = 'even';
		}
		result += '<div class="songItem">';
		result += '<div id="lyric" class="song songLyric ' + style + '"><img src="lib/img/lyric.png" class="showLyric" value="'+curRelease.songs[i][0]+'" id="x' + curRelease.songs[i][2] + '"/></div>';
		result += '<div id="name" value="' + curRelease.songs[i][2] + '" class="song songName ' + style + '">' + curRelease.songs[i][0] + '</div>';
		result += '<div id="duration" value="' + curRelease.songs[i][2] + '" class="song duration ' + style + '">' + curRelease.songs[i][1] + '</div>';
		result += '</div>';
	}
	return result;
}

/** 
 * Open link in user's default browser window.
 * @param {String} href Url to open in external browser
 */
function openExternalURL(href) {
  	var request = new air.URLRequest(href);
  		try {
    	air.navigateToURL(request);
  	} catch (e) {
   	// handle error here
    	air.Introspector.Console.log(e)
  	}
}

/**
 * Reading config file.
 * Creates a configfile if it doesn't excist
 * Sets firstRun to 0
 */
function setConfig() {
	try {
		$xml = $(readFile('config.xml', true));
	} catch(e) {
		writeFile('config.xml',configFile.getXML());
		setConfig();
	}
	var firstRun = $xml.find('firstRun').text();
	configFile.firstRun = firstRun;
	var sqlFile = $xml.find('sqlFile').text();
	configFile.sqlFile = sqlFile;
	var lyrics = $xml.find('lyrics').text();
	configFile.lyrics = lyrics;
	var concert = $xml.find('concert').text();
	configFile.concert = concert;
	var ip = $xml.find('ip').text();
	configFile.ip = ip;
	var location = $xml.find('location').text();
	configFile.location = location;
	var country = $xml.find('country').text();
	configFile.country = country;
	if (configFile.firstRun == 1) {
		createTables();
		configFile.firstRun = 0;
	}
	writeFile('config.xml',configFile.getXML());
	configFile.showConfig();
}

/**
 * Read local files
 * @param {String} fileName Name of the fileto read
 * @param {Boolean} appStoreDir Which directory to read from
 */
function readFile(fileName,appStoreDir){
	if (appStoreDir) {
		var file = air.File.applicationStorageDirectory.resolvePath(fileName);
	}
	else {
		var file = air.File.applicationDirectory.resolvePath(fileName);
	}
    var fs = new air.FileStream();
    fs.open(file, air.FileMode.READ);
    var content = fs.readUTFBytes(fs.bytesAvailable);
    fs.close();
    return content;
}

/**
 * Write to local files
 * @param {String} fileName Filename where to wrtite to
 * @param {String} content congtent of the file
 */
function writeFile(fileName, content){
    var file = air.File.applicationStorageDirectory.resolvePath(fileName);
	var fs = new air.FileStream();
    fs.open(file, air.FileMode.WRITE);
    var content = fs.writeMultiByte(content, air.File.systemCharset);
    fs.close();
}

/**
 * Show tooltip on mouseOver
 * @param {String} message Message which will be in the tooltip. 
 * 						   This text is set in the title of the hoverobject.
 * @param {Object} e Given for mousepositioning
 */
function showTooltip(message,e) {
	timeoutId = setTimeout(hideTooltip, 2000);
	
	$('#tooltip').text(message);
	var toolWidth = $('#tooltip').width();
	var x = e.pageX - 15
	var y = e.pageY - ($('#tooltip').height() + 10)
	if (x + toolWidth > $(window).width()) {
		x = $(window).width() - toolWidth - 10;
	}
	if (y - $('#tooltip').height() < 0) {
		y = 40;
	}
	$('#tooltip').show(250)
				 .css('top', y)
				 .css('left', x)
				 .css('visibility', 'visible');
}

/**
 * Hiding the tooltip after MouseOut or the time settedby the timeout
 */
function hideTooltip() {
	clearTimeout(timeoutId);
	$('#tooltip').hide(250);
}

/**
 * Checking for networkconnection
 */
function checkConnection() {
	connUrl = new air.URLMonitor(new air.URLRequest('http://www.adobe.com'));
	connUrl.addEventListener( air.StatusEvent.STATUS, function(e) {
		if(!e.target.available) {
			bConnection = false;
			air.trace('Geen netwerk meer.');
		}
		else {
			bConnection = true;
			air.trace('Er is verbinding met netwerk');
		}
	});
	connUrl.start();
}
